<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android,IPC," />





  <link rel="alternate" href="/atom.xml" title="GrantonZhuang's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="ContentProvider 是 Android 四大组件之一，主要用于不同的应用之间（也就是不同的进程之间）进行数据的共享。底层也是由 Binder 实现，这篇文章主要讲 ContentProvider 的基本用法，不涉及底层的实现。

Socket 在网络通信中的应用非常的广泛，同样也可以应用在 Android IPC 的场景之中，(网络通信本质上也是跨进程通信)，这篇文章记录使用 Soc">
<meta property="og:type" content="article">
<meta property="og:title" content="Android IPC 学习笔记 3 使用 ContentProvider, Socket 进行进程间通信">
<meta property="og:url" content="https://grantonzhuang.github.io/2016/06/26/AndroidIPC学习笔记3/index.html">
<meta property="og:site_name" content="GrantonZhuang's Blog">
<meta property="og:description" content="ContentProvider 是 Android 四大组件之一，主要用于不同的应用之间（也就是不同的进程之间）进行数据的共享。底层也是由 Binder 实现，这篇文章主要讲 ContentProvider 的基本用法，不涉及底层的实现。

Socket 在网络通信中的应用非常的广泛，同样也可以应用在 Android IPC 的场景之中，(网络通信本质上也是跨进程通信)，这篇文章记录使用 Soc">
<meta property="og:updated_time" content="2016-07-29T13:56:02.584Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android IPC 学习笔记 3 使用 ContentProvider, Socket 进行进程间通信">
<meta name="twitter:description" content="ContentProvider 是 Android 四大组件之一，主要用于不同的应用之间（也就是不同的进程之间）进行数据的共享。底层也是由 Binder 实现，这篇文章主要讲 ContentProvider 的基本用法，不涉及底层的实现。

Socket 在网络通信中的应用非常的广泛，同样也可以应用在 Android IPC 的场景之中，(网络通信本质上也是跨进程通信)，这篇文章记录使用 Soc">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://grantonzhuang.github.io/2016/06/26/AndroidIPC学习笔记3/"/>

  <title> Android IPC 学习笔记 3 使用 ContentProvider, Socket 进行进程间通信 | GrantonZhuang's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">GrantonZhuang's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android IPC 学习笔记 3 使用 ContentProvider, Socket 进行进程间通信
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-06-26T15:55:34+08:00" content="2016-06-26">
              2016-06-26
            </time>
          </span>

          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <ul>
<li><p>ContentProvider 是 Android 四大组件之一，主要用于不同的应用之间（也就是不同的进程之间）进行数据的共享。底层也是由 Binder 实现，这篇文章主要讲 ContentProvider 的基本用法，不涉及底层的实现。</p>
</li>
<li><p>Socket 在网络通信中的应用非常的广泛，同样也可以应用在 Android IPC 的场景之中，(网络通信本质上也是跨进程通信)，这篇文章记录使用 Socket 进行进程间通信的学习笔记。</p>
</li>
</ul>
<a id="more"></a>
<h2 id="ContentProvider"><a href="#ContentProvider" class="headerlink" title="ContentProvider"></a>ContentProvider</h2><h3 id="创建一个-ContentProvider"><a href="#创建一个-ContentProvider" class="headerlink" title="创建一个 ContentProvider"></a>创建一个 ContentProvider</h3><p>创建一个 ContentProvider 只需要继承类 ContentProvider，并且实现六个抽象方法。</p>
<ul>
<li><code>onCreate()</code> ContentProvider 被创建的时候调用，运行在主线程，一般 ContentProvider 采用 SQLite 存储和共享数据，但是也可以采用文件存储，甚至是内存存储，如果采用 SQLite 应该在这个方法进行初始化。</li>
<li><code>getType()</code> 返回共享的数据的 MIME 类型，如音乐，图片等，可以留空。</li>
<li><code>query()</code> 对应增删改查的查，运行在 Binder 线程中。</li>
<li><code>update()</code> 对应增删改查的改，运行在 Binder 线程中。</li>
<li><code>delete()</code> 对应增删改查的删，运行在 Binder 线程中。</li>
<li><code>insert()</code> 对应增删改查的增，运行在 Binder 线程中。</li>
</ul>
<p>举个栗子</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BookProvider</span> <span class="keyword">extends</span> <span class="title">ContentProvider</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = BookProvider.class.getSimpleName();</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String AUTH = <span class="string">"us.igrant.aidlcontentprovider.BookProvider"</span>;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * <span class="doctag">@return</span> true if the provider was successfully loaded, false otherwise</div><div class="line">     * 如果该 ContentProvider 成功加载，返回 true 否则返回 false</div><div class="line">     */</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onCreate</span><span class="params">()</span> </span>&#123;</div><div class="line">        Log.d(TAG, <span class="string">"onCreate: "</span> + Thread.currentThread().getName());</div><div class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Nullable</span></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> Cursor <span class="title">query</span><span class="params">(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)</span> </span>&#123;</div><div class="line">        Log.d(TAG, <span class="string">"query: "</span> + Thread.currentThread().getName());</div><div class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Nullable</span></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getType</span><span class="params">(Uri uri)</span> </span>&#123;</div><div class="line">        Log.d(TAG, <span class="string">"getType: "</span> + Thread.currentThread().getName());</div><div class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Nullable</span></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> Uri <span class="title">insert</span><span class="params">(Uri uri, ContentValues values)</span> </span>&#123;</div><div class="line">        Log.d(TAG, <span class="string">"insert: "</span> + Thread.currentThread().getName());</div><div class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">delete</span><span class="params">(Uri uri, String selection, String[] selectionArgs)</span> </span>&#123;</div><div class="line">        Log.d(TAG, <span class="string">"delete: "</span> + Thread.currentThread().getName());</div><div class="line">        <span class="keyword">return</span> <span class="number">0</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">update</span><span class="params">(Uri uri, ContentValues values, String selection, String[] selectionArgs)</span> </span>&#123;</div><div class="line">        Log.d(TAG, <span class="string">"update: "</span> + Thread.currentThread().getName());</div><div class="line">        <span class="keyword">return</span> <span class="number">0</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>并且在 AndroidManiFest.xml 中声明</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">provider</span></span></div><div class="line">    <span class="attr">android:name</span>=<span class="string">".BookProvider"</span></div><div class="line">    <span class="attr">android:authorities</span>=<span class="string">"us.igrant.aidlcontentprovider.BookProvider"</span></div><div class="line">    <span class="attr">android:permission</span>=<span class="string">"us.igrant.BOOK_PROVIDER"</span></div><div class="line">    <span class="attr">android:process</span>=<span class="string">":provider"</span> /&gt;</div></pre></td></tr></table></figure>
<ul>
<li><code>name</code> Provider 的名字。</li>
<li><code>authorities</code> 可以理解为 Provider 的 URI 链接，采用包名 + 类名。</li>
<li><code>permission</code> 权限，外部应用使用该 ContentProvider 的时候需要声明此权限，参考 Android 自带权限的写法，包名 + 全大写的权限名，除此之外，还有读写权限的区分，这里的 permission 包含了读和写的权限。</li>
<li><code>process</code> 运行在独立的进程中。</li>
</ul>
<p>在 Activity 调用这个 ContentProvider</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainActivity</span> <span class="keyword">extends</span> <span class="title">AppCompatActivity</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@TargetApi</span>(Build.VERSION_CODES.JELLY_BEAN)</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</div><div class="line">        setContentView(R.layout.activity_main);</div><div class="line"></div><div class="line">        <span class="comment">// 这里需要用到在 AndroidManiFest.xml 文件中声明的 auth</span></div><div class="line">        Uri uri = Uri.parse(<span class="string">"content://"</span> + BookProvider.AUTH);</div><div class="line">        getContentResolver().query(uri, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>);</div><div class="line">        getContentResolver().query(uri, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>);</div><div class="line">        getContentResolver().query(uri, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">null</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>Log 输出在 provider 线程中，可以看出 query 方法运行在 Binder 线程池中，我们没有办法控制它运行在具体哪一个线程中。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">06-26 04:27:21.393 22881-22881/? D/BookProvider: onCreate: main</div><div class="line">06-26 04:27:21.393 22881-22893/? D/BookProvider: query: Binder_2</div><div class="line">06-26 04:27:21.393 22881-22892/? D/BookProvider: query: Binder_1</div><div class="line">06-26 04:27:21.393 22881-22893/? D/BookProvider: query: Binder_2</div></pre></td></tr></table></figure>
<h3 id="使用-URIMatcher-区分要操作的数据表"><a href="#使用-URIMatcher-区分要操作的数据表" class="headerlink" title="使用 URIMatcher 区分要操作的数据表"></a>使用 URIMatcher 区分要操作的数据表</h3><p>如果一个 ContentProvider 不只存储一类数据，那么需要使用 UriMatcher 来区分请求操作的是哪一种数据。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String BOOK_TABLE_NAME = <span class="string">"books"</span>;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> BOOK_URI_CODE = <span class="number">1</span>;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String USER_TABLE_NAME = <span class="string">"users"</span>;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> USER_URI_CODE = <span class="number">2</span>;</div><div class="line"></div><div class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> UriMatcher mUriMatcher = <span class="keyword">new</span> UriMatcher(UriMatcher.NO_MATCH);</div><div class="line"></div><div class="line"><span class="comment">// 静态加载，将 Code 和 tableName 一一对应起来</span></div><div class="line"><span class="keyword">static</span> &#123;</div><div class="line">    mUriMatcher.addURI(AUTH, BOOK_TABLE_NAME, BOOK_URI_CODE);</div><div class="line">    mUriMatcher.addURI(AUTH, USER_TABLE_NAME, USER_URI_CODE);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * 根据 URI 获取到表名</div><div class="line"> *</div><div class="line"> * 在增删改查的方法中先调用这个方法得到表名，再进行下一步操作</div><div class="line"> *</div><div class="line"> * <span class="doctag">@param</span> uri</div><div class="line"> * <span class="doctag">@return</span></div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> String <span class="title">getTableName</span><span class="params">(Uri uri)</span> </span>&#123;</div><div class="line">    <span class="keyword">int</span> code = mUriMatcher.match(uri);</div><div class="line">    <span class="keyword">if</span> (BOOK_URI_CODE == code) &#123;</div><div class="line">        <span class="keyword">return</span> BOOK_TABLE_NAME;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (USER_URI_CODE == code) &#123;</div><div class="line">        <span class="keyword">return</span> USER_TABLE_NAME;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>则访问数据表的 URI 变为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Uri uri = Uri.parse(<span class="string">"content://"</span> + BookProvider.AUTH + <span class="string">"/"</span> + BookProvider.USER_TABLE_NAME);</div></pre></td></tr></table></figure>
<p>这样子，就可以使用一个 ContentProvider 提供多种类型的数据了。</p>
<blockquote>
<p>最后，需要注意的是，ContentProvider 提供的数据操作，是多线程并发访问的，如果使用 SQLite，一个 SQLiteDataBase 对象内部则进行了线程同步，但是多个 SQLiteDataBase 或者说其他的存储方法，如内存，文件存储等，则需要做好同步的工作应对并发访问。</p>
</blockquote>
<h2 id="Socket"><a href="#Socket" class="headerlink" title="Socket"></a>Socket</h2><h3 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h3><p>使用 Java 原生的 API 即可建立一个 Socket 服务端，在 Android 中，网络通信需要放在子线程中，比如以下写法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">	        <span class="keyword">int</span> PORT = <span class="number">8888</span>;</div><div class="line">            ServerSocket serverSocket = <span class="keyword">new</span> ServerSocket(PORT);</div><div class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;).run();</div></pre></td></tr></table></figure>
<p>接收一个 Socket 客户端</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">try</span> &#123;</div><div class="line">    <span class="keyword">final</span> Socket client = serverSocket.accept();</div><div class="line">&#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">    e.printStackTrace();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>获取客户端的输入流和输出流，用以读取客户端输入的信息和向客户端输出信息</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">BufferedReader reader = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(client.getInputStream()));</div><div class="line"></div><div class="line">PrintWriter printWriter = <span class="keyword">new</span> PrintWriter(<span class="keyword">new</span> BufferedWriter( <span class="keyword">new</span> OutputStreamWriter(client.getOutputStream())), <span class="keyword">true</span>);</div></pre></td></tr></table></figure>
<h3 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h3><p>建立一个 Socket 连接，在 Android 中，网络通信需要放在子线程中，比如以下写法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        String address = <span class="string">"localhost"</span>;</div><div class="line">        <span class="keyword">int</span> PORT = <span class="number">8888</span>;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            Socket socket = <span class="keyword">new</span> Socket(address, PORT);</div><div class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;).run();</div></pre></td></tr></table></figure>
<p>获取客户端的输入流和输出流，用以读取服务端输入的信息和向服务端输出信息。</p>
<p><strong>输入与输出都是相对的说法，服务端的输入即是客户端的输出，客户端的输入即是服务端的输出。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">BufferedReader reader = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(socket.getInputStream()));</div><div class="line"></div><div class="line">PrintWriter printWriter = <span class="keyword">new</span> PrintWriter(<span class="keyword">new</span> BufferedWriter( <span class="keyword">new</span> OutputStreamWriter(socket.getOutputStream())), <span class="keyword">true</span>);</div></pre></td></tr></table></figure>
<blockquote>
<p>需要注意的是，不同于 AIDL 的通信方式，Socket 只能传递字节流，PrintWriter 也只支持基本数据类型和 String 类型，并没有对 Parcelable 对象进行支持。因此，常见的跨进程通信的场景，我们还是很少使用 Socket 来作为解决方案的。</p>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag">#Android</a>
          
            <a href="/tags/IPC/" rel="tag">#IPC</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/06/14/AndroidIPC学习笔记2/" rel="next" title="Android IPC 学习笔记 2 使用 AIDL 进行进程间通信进阶">
                <i class="fa fa-chevron-left"></i> Android IPC 学习笔记 2 使用 AIDL 进行进程间通信进阶
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/07/01/AndroidIPC学习笔记4/" rel="prev" title="Android IPC 学习笔记 4 Binder 连接池">
                Android IPC 学习笔记 4 Binder 连接池 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://ww1.sinaimg.cn/mw690/6e8939a6gw1f3g1u1mc6lj20hs0hsmxf.jpg"
               alt="Granton Zhuang" />
          <p class="site-author-name" itemprop="name">Granton Zhuang</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives/index.html">
              <span class="site-state-item-count">26</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#ContentProvider"><span class="nav-number">1.</span> <span class="nav-text">ContentProvider</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建一个-ContentProvider"><span class="nav-number">1.1.</span> <span class="nav-text">创建一个 ContentProvider</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-URIMatcher-区分要操作的数据表"><span class="nav-number">1.2.</span> <span class="nav-text">使用 URIMatcher 区分要操作的数据表</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Socket"><span class="nav-number">2.</span> <span class="nav-text">Socket</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端"><span class="nav-number">2.1.</span> <span class="nav-text">服务端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端"><span class="nav-number">2.2.</span> <span class="nav-text">客户端</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Granton Zhuang</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  

  

  

</body>
</html>
